package com.xhsj.user.hr.process.message.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.hr.base.BaseService;
import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.process.message.entity.TbProjectMessage;
import com.xhsj.user.hr.process.message.mapper.TbProjectMessageMapper;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.pms.patent.query.TbProjectMessageQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.utils.AliyunMessage;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * <p>
 * 项目消息 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since 2020-04-01
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbProjectMessage")
public class TbProjectMessageService extends ServiceImpl<TbProjectMessageMapper, TbProjectMessage> {

//    public static ConcurrentLinkedQueue<Map<String, String>> vo = new ConcurrentLinkedQueue();

    public static final LinkedBlockingQueue<Map<String, String>> queue = new LinkedBlockingQueue(100);

    @Autowired
    private TbProjectMessageMapper dao;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper userMapper;

    @Override
    //@CacheEvict(cacheNames="TbProjectMessage", allEntries=true)
    public boolean save(TbProjectMessage entity) {
        return super.save(entity);
    }

    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbProjectMessage getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    //@CacheEvict(cacheNames="TbProjectMessage", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }


    public IPage<TbProjectMessage> detailByUserId(String userId, String status, int currentPage, int pageSize, String projectId) {
        Page<TbProjectMessage> page = new Page(currentPage,pageSize);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("recipient",userId);
        wrapper.eq("status",status);
        wrapper.eq("project_id",projectId);
        return dao.selectPage(page,wrapper);
    }


    public void sendMessage(String phoneNumber, String moudleName,int count,String name) {
        Message message = AliyunMessage.sendSms(phoneNumber, moudleName,name);
        String code = String.valueOf(message.get("code"));
        if ("1".equals(code)) {// 发送失败
            Map<String, String> map = Maps.newHashMap();
            map.put("phone",phoneNumber);
            map.put("moudleName",moudleName);
            map.put("count",String.valueOf(count));
            map.put("name",name);
            try {
                TbProjectMessageService.queue.put(map);
            } catch (InterruptedException e) {
                log.error("队列添加出错",e);
            }
        }
    }

    public void sendMessageCommon(ApprovalQuery data) {

        // 获取接收者
		List<Long> receiveUserIds = this.handleReceiveUserIds(data);
		// 消息发送
		Map<String, Object> messageMap = Maps.newHashMap();
		messageMap.put("projectId",data.getProjectId());
		messageMap.put("dataId", data.getDataId()); // 业务id
		messageMap.put("title", data.getTitle()); // 标题
		messageMap.put("sender", data.getCurrentUserId()); // 发送者
		messageMap.put("userIds", receiveUserIds);
		messageMap.put("name", data.getCreateName());
		applicationContext.publishEvent(new MessageEvent(this, messageMap));
	}

    /**
     *获取接收者
     * @param data
     * @return
     */
    private List<Long> handleReceiveUserIds(ApprovalQuery data) {
        List<Long> list = Lists.newArrayList();
        Object userId = data.getUserId();
        if (!Objects.isNull(userId)) {
            List<Long> userIds = JSONArray.parseArray(String.valueOf(userId), Long.class);
            list.addAll(userIds);
        }
        Object roleIds = data.getRoleIds();
        if (!Objects.isNull(roleIds)) {
            List<Long> roles = JSONArray.parseArray(String.valueOf(roleIds), Long.class);
            List<Long> userIds = tbGlobalUserService.getUserListByRoleIds(roles);
            list.addAll(userIds);
        }
        return list;
    }


    public List<TbProjectMessage> getSendMessageList() {
        List<TbProjectMessage> sendMessageQuery = new ArrayList<>();
        List<TbProjectMessageQuery> sendMessageList = dao.getSendMessageList();
        for (TbProjectMessageQuery sendMessage: sendMessageList) {
            if (sendMessage.getRecipient().equals(sendMessage.getIdentitylinkUserId())) {
                TbProjectMessage tbProjectMessage = StringUtils.toJavaBean(sendMessage,TbProjectMessage.class);
                sendMessageQuery.add(tbProjectMessage);
            }else{
                // 角色对应的用户
                List<Long> roleList = new ArrayList<>();
                roleList.add(sendMessage.getIdentitylinkGroupId());
                List<String> userInfoByRoleId = userMapper.getUserInfoByRoleId(roleList);
                if (userInfoByRoleId != null) {
                    if (userInfoByRoleId.contains(sendMessage.getRecipient())) {
                        TbProjectMessage tbProjectMessage = StringUtils.toJavaBean(sendMessage,TbProjectMessage.class);
                        sendMessageQuery.add(tbProjectMessage);
                    }
                }

            }
        }
        return sendMessageQuery;
    }


    /**
     * 给手机App查询消息
     * @author 苏小林
     * @date 2021/4/19 16:50
     * @return: java.util.List<java.lang.String>
     */
    public List<Map<String,Object>> findAppMessage() {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0));

        LocalDateTime endDate = LocalDateTime.of(LocalDate.now().plusDays(7), LocalTime.of(0, 0, 0));
        return dao.findAppMessage(userId,startDate,endDate);
    }

}
